package cn.wolfcode.wolf2w.redis.impl;

import cn.wolfcode.wolf2w.domain.Visitor;
import cn.wolfcode.wolf2w.redis.IVisitorRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.redis.vo.VisitorVo;
import cn.wolfcode.wolf2w.repository.VisitorRepsitory;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.SocketUtils;
import org.springframework.util.StringUtils;

import java.util.List;

//访客
@Service
public class VisitorRedisServiceImpl implements IVisitorRedisService {

    @Autowired
    private VisitorRepsitory repsitory;

    @Autowired
    private StringRedisTemplate template;

    //容易让mongodb产生误会,后续自动生成的id不会存进去
    @Override
    public void save(Visitor visitor) {
        repsitory.save(visitor);
    }

    @Override
    public void update(Visitor visitor) {
        repsitory.save(visitor);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public Visitor get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<Visitor> list() {
        return repsitory.findAll();
    }


    @Override
    public VisitorVo queryNumByuid(String id, String oid) {
        String key = RedisKeys.VISITOR_VO.join(id);
        System.out.println(id);
        VisitorVo vo = null;
        if (!template.hasKey(key)) {
            vo = new VisitorVo();
            Visitor visitor = repsitory.findByUserId(id);
            System.out.println(visitor);
            BeanUtils.copyProperties(visitor, vo);
        } else {
            String s = template.opsForValue().get(key);
            vo = JSON.parseObject(s, VisitorVo.class);
            if (!id.equals(oid)) {
                vo.setCount(vo.getCount() + 1);
                vo.setTotal(vo.getTotal() + 1);
            }
        }
        template.opsForValue().set(key, JSON.toJSONString(vo));
        return vo;
    }
}
